package com.zlyx.easy.access;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.context.ApplicationContext;

import com.zlyx.easy.access.annotations.EasyAccesser;
import com.zlyx.easy.access.interfaces.IDataAccesser;
import com.zlyx.easy.core.refresh.IHandlerOnRefreshed;
import com.zlyx.easy.core.refresh.annotations.RefreshBean;
import com.zlyx.easy.core.spring.SpringUtils;
import com.zlyx.easy.core.utils.ObjectUtils;
import com.zlyx.easy.core.utils.StringUtils;

/**
 * @Auth 赵光
 * @Describle
 * @2019年1月11日 下午5:40:32
 */
@RefreshBean(todo = { "访问层管理平台" })
public class AccesserManager implements IHandlerOnRefreshed {

	private static Map<String, IDataAccesser> factorys = new ConcurrentHashMap<>();

	@Override
	public void doOnRefreshed(ApplicationContext context) {
		Map<String, IDataAccesser> beans = SpringUtils.getBeansOfType(IDataAccesser.class);
		EasyAccesser accesserAnno = null;
		for (String beanName : beans.keySet()) {
			accesserAnno = beans.get(beanName).getClass().getAnnotation(EasyAccesser.class);
			if (ObjectUtils.isNotEmpty(accesserAnno) && ObjectUtils.isNotEmpty(accesserAnno.value())) {
				factorys.put(accesserAnno.value(), beans.get(beanName));
			}
		}
	}

	public static int size() {
		return factorys.size();
	}

	public static IDataAccesser getAccesser(String key) {
		if (StringUtils.isEmpty(key) || factorys.size() == 1) {
			return SpringUtils.getBean("defaultAccesser");
		}
		return factorys.get(key);
	}

	public static List<IDataAccesser> getAccessers() {
		return new ArrayList<IDataAccesser>(factorys.values());
	}
}
